package com.alex.cms.web.controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alex.cms.domain.CmsChannel;
import com.alex.cms.domain.CmsUser;
import com.alex.cms.service.ICmsChannelService;
import com.alex.cms.web.constants.CMSConstants;
import com.alex.cms.web.form.ChannelForm;
import com.alex.cms.web.vo.ResultVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bawei.common.Exception.CMSSystemException;
import com.bawei.common.utils.AssertionUtil;

/**
 * <p>
 * 栏目表 前端控制器
 * </p>
 *
 * @author alex
 * @since 2019-09-11
 */
@Controller
@RequestMapping("/channel")
public class CmsChannelController {

	@Autowired
	public ICmsChannelService channelService;

	@RequestMapping("/toAddchannel")
	public ModelAndView showChannel() {
		// 指定跳转的jsp页面
		ModelAndView mav = new ModelAndView("/admin/channel-edit");
		// 页面需要的分类信息
		ChannelForm channelForm = new ChannelForm();
		mav.addObject("channel", channelForm);
		return mav;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView editchannel(ChannelForm channelForm, MultipartFile file, HttpSession session, @RequestParam(required = false, name = "isDelCover") Integer isDelCover) {
		// 获取登录时保存到session的用户信息
		CmsUser user = (CmsUser) session.getAttribute(CMSConstants.LOGIN_USER);
		// 指定文章发布成功跳转到哪个页面（/channel/list?userid=xxxx这是文章列表的url
		ModelAndView mav = new ModelAndView("redirect:/admin/channels");
		CmsChannel channel = new CmsChannel();
		String fileName = "";
		/********* 文章修改的功能 *********/
		if (file.isEmpty()) {
			// 判断前端的cover参数是否有值
			if (channelForm.getIcon() != null) {
				// isDelCover：是否删除，1为删除图片
				if (isDelCover == 1) {
					// 构造要被删除的封面图片文件对象
					File deleteFile = new File(session.getServletContext().getRealPath("/") + channelForm.getIcon());
					// java.io.File的判断方法，判断文件是否存在
					if (deleteFile.exists()) {
						// java.io.File的删除方法
						deleteFile.delete();
					}
				}
			}
			/******** 文章修改的功能 **********/
		} else {
			// 图片上传的功能
			// 获取图片文件的原始文件名
			String name = file.getOriginalFilename();
			// 获取文件的后缀名，比如：.jpg .txt....
			String suffix = name.substring(name.lastIndexOf("."));
			// 上传后的文件名，随机生成一个唯一的UUID
			fileName = UUID.randomUUID().toString() + suffix;
			// 文件保存路径，一般实际开发中的fastfds文件服务器指定路径
			File file2 = new File(session.getServletContext().getRealPath("/") + CMSConstants.FILE_SAVE_PATH);
			// 判断文件路径是否存在，不存在重新创建
			if (!file2.exists()) {
				// java.io.File的创建文件路径
				file2.mkdir();
				// java.io.File的设置权限的方法，读写权限
				// file2.canExecute();
				// file2.canRead();
				// file2.canWrite();
			}
			File picFile = new File(session.getServletContext().getRealPath("/") + CMSConstants.FILE_SAVE_PATH + fileName);
			// spring的上传功能
			try {
				file.transferTo(picFile);
			} catch (Exception e1) {
				mav.addObject("message", "文章上传失败！");
				mav.addObject("blog", channelForm);
				mav.setViewName("user-space/blog_edit");
			}
		}
		// 文章编辑功能
		if (!file.isEmpty()) {
			// 如果没有提交封面图片，则设置该字段为null
			channel.setIcon(CMSConstants.FILE_SAVE_PATH + fileName);
		} else {
			if (channelForm.getIcon() != null) {
				if (isDelCover == 1) {
					// 如果设置实体属性值为null，mybatis-plus将不会修改相应的字段
					channel.setIcon("");
				} else {
					// 如果原来有封面，则使用原来的图片
					channel.setIcon(channelForm.getIcon());
				}
			} else {
				// 如果原来封面，则设置为null
				channel.setIcon("");
			}
		}

		// 保存文章
		if (channelForm.getId() != null) {
			channel.setId(channelForm.getId());
		}
		channel.setName(channelForm.getName());
		channel.setDescription(channelForm.getDescription());
		List<CmsChannel> list = channelService.list(new QueryWrapper<CmsChannel>().orderByDesc("sorted"));
		if (channelForm.getId() == null) {
			channel.setSorted(list.get(0).getSorted() + 1);
		}
		channelService.saveOrUpdate(channel);
		return mav;
	}

	@RequestMapping("/upMove")
	public ModelAndView moveUp(@RequestParam("channelId") Integer channelId) {
		ModelAndView mav = new ModelAndView("redirect:/admin/channels");
		QueryWrapper<CmsChannel> queryWrapper = new QueryWrapper<CmsChannel>();
		queryWrapper = queryWrapper.orderByAsc("sorted");
		List<CmsChannel> channelList = channelService.list(queryWrapper);
		List<CmsChannel> cList = new ArrayList<CmsChannel>();
		for (int i = 0; i < channelList.size(); i++) {
			if (channelList.get(0).getId() == channelId) {
				break;
			}
			if (i == 0) {
				channelList.get(0).setSorted(channelList.get(channelList.size() - 1).getSorted());
				cList.add(channelList.get(0));
				continue;
			}
			channelList.get(i).setSorted(channelList.get(i).getSorted() - 1);
			cList.add(channelList.get(i));
		}
		channelService.updateBatchById(cList);
		return mav;
	}

	@RequestMapping("/downMove")
	public ModelAndView moveDown(@RequestParam("channelId") Integer channelId) {
		ModelAndView mav = new ModelAndView("redirect:/admin/channels");
		QueryWrapper<CmsChannel> queryWrapper = new QueryWrapper<CmsChannel>();
		queryWrapper = queryWrapper.orderByAsc("sorted");
		List<CmsChannel> channelList = channelService.list(queryWrapper);
		List<CmsChannel> cList = new ArrayList<CmsChannel>();
		for (int i = 0; i < channelList.size(); i++) {
			if (channelList.get(channelList.size() - 1).getId() == channelId) {
				break;
			}
			if (i == channelList.size() - 1) {
				channelList.get(channelList.size() - 1).setSorted(channelList.get(0).getSorted()-1);
				cList.add(channelList.get(channelList.size() - 1));
				continue;
			}
			channelList.get(i).setSorted(channelList.get(i).getSorted() + 1);
			cList.add(channelList.get(i));
		}
		channelService.updateBatchById(cList);
		return mav;
	}

	@RequestMapping("/toEditChannel")
	public ModelAndView showChannelPage(@RequestParam("channelId") Integer channelId) {
		// 指定跳转到哪个jsp，"user-space/blog_edit"是jsp的路径
				ModelAndView mav = new ModelAndView("admin/channel-edit");

				ChannelForm channleForm = new ChannelForm();

				try {
					// 根据文章ID获取文章
					CmsChannel channel = channelService.getById(channelId);

					// 断言要抛出异常，断言之后执行的语句都是正确流程
					AssertionUtil.assertFalse(channel == null, CMSConstants.CHANNEL_IS_NOT_EXIST);

					channleForm.setId(channelId);
					channleForm.setName(channel.getName());
					channleForm.setDescription(channel.getDescription());
					channleForm.setIcon(channel.getIcon());

					// 返回页面数据，"blog"是前端定义的名字
					mav.addObject("channel", channleForm);
				} catch (CMSSystemException e) {
					// 视图仍然定位到文章编辑页面，错误消息在编辑页面显示
					mav.addObject("message", e.getMessage());
				}

				return mav;
	}

	@RequestMapping("/editChannel")
	public ModelAndView editChannel() {
		return null;

	}

	@RequestMapping("/removeChannel")
	@ResponseBody
	public ResultVo removeSettingById(@RequestParam("id") Integer settingId) {
		// ajax定义的返回数据结构，所以定义这个对象的时候看ajax的data结构是什么
		ResultVo result = new ResultVo();
		// 根据配置ID删除，返回结果
		boolean removeResult = channelService.removeById(settingId);
		// 返回结果都统一放在constants中，便于维护
		result.setStatus(removeResult ? CMSConstants.RESULT_STATUS_SUCCESS : CMSConstants.RESULT_STATUS_ERROR);
		result.setMessage(removeResult ? CMSConstants.RESULT_DELETE_MESSAGE_SUCCESS : CMSConstants.RESULT_DELETE_MESSAGE_ERROR);

		return result;
	}
}
